package net.xo68.destiny.core.jwt;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.core.util.UuIdUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt模板
 * @author wuxie
 * @version 2020-11-6
 */
@Slf4j
public class JwtTokenTemplate implements IJwtTokenTemplate {

    /**
     * 签名算法
     */
    private final SignatureAlgorithm signatureAlgorithm;
    /**
     * 签名密钥
     */
    private final String signatureSecret;
    /**
     * 签发人
     */
    private final String issuer;

    public JwtTokenTemplate(String signatureSecret, String issuer) {
        this(SignatureAlgorithm.HS512,signatureSecret,issuer);
    }

    public JwtTokenTemplate(SignatureAlgorithm signatureAlgorithm, String signatureSecret, String issuer) {
        this.signatureAlgorithm = signatureAlgorithm;
        this.signatureSecret = signatureSecret;
        this.issuer=issuer;
    }

    @Override
    public String generateToken(String sub,String aud, long expireSecond){
        return generateToken(UuIdUtils.shortUuId(),sub,aud,null,expireSecond);
    }

    @Override
    public String generateToken(String jtl,String sub,String aud, long expireSecond){
        return generateToken(jtl,sub,aud,null,expireSecond);
    }
    @Override
    public String generateToken(String sub,String aud, Map<String, Object> claims, long expireSecond){
        return generateToken(UuIdUtils.shortUuId(),sub,aud,null,expireSecond);
    }
    @Override
    public String generateToken(String jtl,String sub,String aud, Map<String, Object> claims, long expireSecond){
        if(claims==null){
            claims=new HashMap<>();
        }
        return Jwts.builder()
                .signWith(signatureAlgorithm, signatureSecret)
                .setClaims(claims)
                .setId(jtl)
                .setSubject(sub)
                .setAudience(aud)
                .setIssuer(issuer)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireSecond * 1000))
                .compact();
    }



    /**
     * 解析令牌
     * @param token
     * @return
     */
    @Override
    public JwtTokenParser parse(String token) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException{
        Claims claims= Jwts.parser()
                .setSigningKey(signatureSecret)
                .parseClaimsJws(token)
                .getBody();
        return new JwtTokenParser(claims);
    }
}
